package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.HoneyLogs;
import com.example.springboot.common.LogType;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Enroll;
import com.example.springboot.entity.Grade;
import com.example.springboot.entity.News;
import com.example.springboot.entity.User;
import com.example.springboot.service.EnrollService;
import com.example.springboot.service.GradeService;
import com.example.springboot.service.NewsService;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 功能：报名信息增删查改
 * 作者：刘涵茹
 * 日期：2024/3/23 18:04
 */

@RestController
@RequestMapping("/enroll")
public class EnrollController {
    @Autowired//通过注解去拿@Service注解中注入容器的函数数据
    NewsService newsService;
    @Autowired
    UserService userService;
    @Autowired
    GradeService gradeService;
    @Autowired
    EnrollService enrollService;

    /**
     * 新增信息 post
     */
    @PostMapping("/add")
    @HoneyLogs(operation = "报名", type = LogType.ADD)
    public Result add(@RequestBody Enroll enroll) {
        try {
            User currentUser = TokenUtils.getCurrentUser(); //获取当前登录的用户信息
            enroll.setPartid(currentUser.getId());
            enroll.setCreatedtime(DateUtil.now());
            enroll.setAudit("待审核");
            enroll.setPayfor("待支付");
            enroll.setGrade("待评分");
            //验证同一人不能报相同的竞赛
            QueryWrapper<Enroll>queryWrapper = new QueryWrapper<>();
            queryWrapper.like( "partid", currentUser.getId());
            queryWrapper.like( "newsid", enroll.getNewsid());
            Enroll dbEnroll = enrollService.getOne(queryWrapper);
            //验证时间
            //格式化
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            News news = newsService.getById(enroll.getNewsid());
            String stratime = news.getStartime();
            String endtime = news.getEndtime();
            //把string类型的转换为long类型
            long l=sim.parse(enroll.getCreatedtime()).getTime();
            //把开始区间时间和结束区间时间转换为long类型。然后比较
            long arm1=sim.parse(stratime).getTime();
            long arm2=sim.parse(endtime).getTime();
            if(l > arm1 && l < arm2) {
                if (dbEnroll != null && enroll.getNewsid().equals(dbEnroll.getNewsid())){
                    return Result.error("不能重复报名");
                }else {
                    news.setNum(news.getNum()+1);//报名成功后,报名人数加1
                    newsService.updateById(news);//报名成功后,报名人数加1
                    enrollService.save(enroll);
                }
            }else {
                return Result.error("申请时间不在竞赛报名时间范围内");
            }
        }catch (Exception e) {
                return Result.error("系统错误");//其他报错
            }
        return Result.success();
    }

    /**
     * 修改信息 put
     */
    @PutMapping("/update")
    @HoneyLogs(operation = "报名", type = LogType.UPDATE)
    public Result update(@RequestBody Enroll enroll) {
        try {
            Grade grade = gradeService.getByEnrollId(enroll.getId());
            if (grade == null){
                if (enroll.getPayfor().equals("已支付")){
                    return Result.error("该报名已支付,不可更改");
                }else {
                    enrollService.updateById(enroll);//service中的函数
                }
            }else {
                return Result.error("该报名信息已评分,不可修改");
            }
        } catch (Exception e) {
                return Result.error("系统错误");//其他报错
        }
        return Result.success();
    }

    /**
     * 单个删除信息 delete
     */
    @HoneyLogs(operation = "报名", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")//delete需要通过path相关注解使用
    public Result delete(@PathVariable Integer id) {
        Enroll enroll = enrollService.getById(id);
        if (!enroll.getAudit().equals("已通过")){
            if (enroll.getPayfor().equals("已支付")){
                return Result.error("该报名已支付,不可撤回");
            }else {
                News news = newsService.getById(enroll.getNewsid());
                news.setNum(news.getNum()-1);
                newsService.updateById(news);
                enrollService.removeById(id);//service中的函数
                return Result.success();
            }
        } else {
            return Result.error("该报名已通过审核,不可撤回");
        }
    }

    /**
     * 查询全部的信息
     */
    @GetMapping("/selectAll")
    public Result selectAll() {//得到数组，并传到service中
        List<Enroll> enrollList = enrollService.list(new QueryWrapper<Enroll>().orderByDesc("id"));
        //service中的函数
        //select * from enroll order by id desc
        return Result.success(enrollList);
    }

    /**
     * 单个条件查询
     * 根据id查询单个的信息
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {//得到数组，并传到service中
        Enroll enroll = enrollService.getById(id);//service中的函数
        User user = userService.getById(enroll.getPartid());
        if (user != null){
            enroll.setUsername(user.getUsername());
            enroll.setMajor(user.getMajor());
        }
        return Result.success(enroll);
    }

    /**
     * 分页多个条件模糊查询
     * 查询所有角色的信息
     */
    @GetMapping("/selectByPage")
    public Result selectByPage(
            @RequestParam Integer pageNum,//页数或者页码
            @RequestParam Integer pageSize,//当前页总共有多少条数据 这两个都是前端传参过来的
            @RequestParam String title,
            @RequestParam String sign,
            @RequestParam String teacher
    ) {//得到数组，并传到service中
        QueryWrapper<Enroll>queryWrapper = new QueryWrapper<Enroll>().orderByDesc("id");//默认倒序,让最新的数据在最上面
        queryWrapper.like(StrUtil.isNotBlank(title), "title", title);
        queryWrapper.like(StrUtil.isNotBlank(sign), "sign", sign);
        queryWrapper.like(StrUtil.isNotBlank(teacher), "teacher", teacher);
        Page<Enroll> page = enrollService.page(new Page<>(pageNum, pageSize), queryWrapper);//service中的函数
        List<Enroll> records = page.getRecords();
        for (Enroll recode : records){
            Integer partid = recode.getPartid();
            User user = userService.getById(partid);
            if (user != null){
                recode.setUsername(user.getUsername());
                recode.setMajor(user.getMajor());
            }
//            Integer newsid = recode.getNewsid();
//            News news = newsService.getById(newsid);
//            if (news != null){
//                recode.setPay(news.getPay());
//            }
        }
        return Result.success(page);
    }

    /**
     * 分页多个条件模糊查询
     * 仅查询自己角色的报名信息
     */
    @GetMapping("/selectByUserPage")
    public Result selectByUserPage(
            @RequestParam Integer pageNum,//页数或者页码
            @RequestParam Integer pageSize,//当前页总共有多少条数据 这两个都是前端传参过来的
            @RequestParam String title,
            @RequestParam String sign,
            @RequestParam String teacher
    ) {//得到数组，并传到service中
        User currentUser = TokenUtils.getCurrentUser(); //获取当前登录的用户信息
        Integer partid = currentUser.getId();
        QueryWrapper<Enroll>queryWrapper = new QueryWrapper<Enroll>().orderByDesc("id");//默认倒序,让最新的数据在最上面
        queryWrapper.like(StrUtil.isNotBlank(title), "title", title);
        queryWrapper.like(StrUtil.isNotBlank(sign), "sign", sign);
        queryWrapper.like(StrUtil.isNotBlank(teacher), "teacher", teacher);
        queryWrapper.like( "partid", partid);
        Page<Enroll> page = enrollService.page(new Page<>(pageNum, pageSize), queryWrapper);//service中的函数
        List<Enroll> records = page.getRecords();
        for (Enroll recode : records){
            User user = userService.getById(partid);
            if (user != null){
                recode.setUsername(user.getUsername());
                recode.setMajor(user.getMajor());
            }
//            Integer newsid = recode.getNewsid();
//            News news = newsService.getById(newsid);
//            if (news != null){
//                recode.setPay(news.getPay());
//            }
        }
        return Result.success(page);
    }

    /**
     * 分页多个条件模糊查询
     * 在成绩评分中显示符合条件的报名信息(审核通过 && (支付成功 || 不需支付) && 待评分)
     */
    @GetMapping("/selectByFitPage")
    public Result selectByFitPage(
            @RequestParam Integer pageNum,//页数或者页码
            @RequestParam Integer pageSize,//当前页总共有多少条数据 这两个都是前端传参过来的
            @RequestParam String title,
            @RequestParam String sign,
            @RequestParam String teacher
    ) {//得到数组，并传到service中
        QueryWrapper<Enroll>queryWrapper = new QueryWrapper<Enroll>().orderByDesc("id");
        queryWrapper.eq("grade","待评分");
        queryWrapper.eq( "audit", "已通过");
        queryWrapper.eq( "pay", "免费").or().eq("payfor","已支付");
        queryWrapper.eq("grade","待评分");//就是要两个(免费-待评分,已支付-待评分),前后各一个
        queryWrapper.like(StrUtil.isNotBlank(title), "title", title);
        queryWrapper.like(StrUtil.isNotBlank(sign), "sign", sign);
        queryWrapper.like(StrUtil.isNotBlank(teacher), "teacher", teacher);
        Page<Enroll> page = enrollService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<Enroll> records = page.getRecords();
        for (Enroll recode : records){
            Integer partid = recode.getPartid();
            User user = userService.getById(partid);
            if (user != null){
                recode.setUsername(user.getUsername());
                recode.setMajor(user.getMajor());
            }
        }

        return Result.success(page);
    }
}
